package application

import (
	"fmt"

	"baseService/internal/global"
	"baseService/internal/infrastructure/config"
	"baseService/internal/infrastructure/persistence"
	"baseService/internal/pkg/cache"
	"baseService/internal/pkg/eventbus"
	"baseService/internal/pkg/logger"

	"baseService/internal/application/services"
	"baseService/internal/domain/repositories"

	"gorm.io/gorm"
)

// AppContext 聚合应用运行所需的核心依赖，便于显式传递
type AppContext struct {
	Config    *config.Config
	Logger    logger.Logger
	DB        *gorm.DB
	Cache     cache.Cache
	EventBus  *eventbus.EventBus
	DBManager *persistence.DatabaseManager

	userRepo    repositories.UserRepository
	userService *services.UserService
}

// NewAppContext 从已初始化的 global 包导出依赖
func NewAppContext() (*AppContext, error) {
	if !global.IsInitialized() {
		return nil, fmt.Errorf("全局组件未初始化")
	}

	return &AppContext{
		Config:    global.Config,
		Logger:    global.Logger,
		DB:        global.DB,
		Cache:     global.Cache,
		EventBus:  global.EventBus,
		DBManager: global.DBManager,
	}, nil
}

// UserRepository 懒加载用户仓储
func (ctx *AppContext) UserRepository() repositories.UserRepository {
	if ctx.userRepo == nil {
		ctx.userRepo = persistence.NewUserRepository(ctx.DB)
	}
	return ctx.userRepo
}

// UserService 懒加载用户服务
func (ctx *AppContext) UserService() *services.UserService {
	if ctx.userService == nil {
		ctx.userService = services.NewUserService(ctx.UserRepository(), ctx.Logger)
	}
	return ctx.userService
}

// IsProduction 判断是否生产环境
func (ctx *AppContext) IsProduction() bool {
	return ctx.Config != nil && ctx.Config.IsProduction()
}

// IsDevelopment 判断是否开发环境
func (ctx *AppContext) IsDevelopment() bool {
	return ctx.Config != nil && ctx.Config.IsDevelopment()
}

// GetConnectionStats 获取数据库连接池状态
func (ctx *AppContext) GetConnectionStats() (map[string]interface{}, error) {
	if ctx.DBManager == nil {
		return nil, fmt.Errorf("数据库管理器未初始化")
	}
	return ctx.DBManager.GetConnectionStats()
}
